/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    TouchableWithoutFeedback,
    InteractionManager,
    Alert,
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsItem from '../components/GoodsItem';
import ImageCropPicker from 'react-native-image-crop-picker';
import StorageUser from '../lib/plugins/StorageUser';
import shopService from '../lib/services/shopService';
import LoadingModal from '../components/LoadingModal';
var FileUpload = require('NativeModules').FileUpload;
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class AddGoods extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.shopId = '';
        this.state = {
            staturs:this.props.navigation.state.params.staturs,
            g_id:this.props.navigation.state.params.g_id || '',
            selectIndex:0,
            resultImageData : {},
            avatarSource:{},
            g_cate:'',
            g_num:'',
            g_num_danger:'',
            g_price:'',
            g_get_price:'',
            g_name:'',
            goodsData:{},
            g_is_show:1,
            swiperImageUrl:[],
            swiperImageData:[],
            detailImageUrl:[],
            detailImageData:[],
            g_jieshao:'',
            load:false,
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                if(data.shopId){
                    $this.shopId = data.shopId;
                }
                InteractionManager.runAfterInteractions(() => {
                    if($this.state.g_id){
                        $this.getGoodsData();
                    }
                });              
            }).catch(err=> {
                console.log(err)
            });
    }
    // 渲染添加的多张图片
    renderImages(staturs,list){
        return(
            list.map((item,i)=>{
                return(
                    <View key={i}>
                        <TouchableOpacity style={{paddingTop:10,paddingRight:10}} onPress={()=>this.selectItem(staturs,i)}>
                            <ImageWrapper style={{width:20,height:20,position:'absolute',top:0,right:0,zIndex:1000}} icon={'stop'}/>
                            <Image style={{width:60,height:60}} source={{uri:item.path}}/>         
                        </TouchableOpacity>
                    </View>
                )
            })
        )
    }
    renderButton(){
        if(this.state.g_is_show==1){
            return(
                <TouchableOpacity onPress={()=>this.clickButton('g_is_show')} style={styles.buttonBox}>
                    <View style={[styles.button,{backgroundColor:'#FF0000'}]}>
                        <Text style={{color:'#fff'}}>下架</Text>
                    </View>
                </TouchableOpacity>
            )
        }else{
            return(
                <TouchableOpacity onPress={()=>this.clickButton('g_is_show')} style={styles.buttonBox}>
                    <View style={[styles.button,{backgroundColor:'#0894ED'}]}>
                        <Text style={{color:'#fff'}}>上架</Text>
                    </View>
                </TouchableOpacity>
            )
        }
                            
    }
    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={this.state.staturs} 
                    leftPress={()=>this.goBack()}
                    rightText={this.state.staturs=='添加商品'?'':'完成'}
                    rightTextStyle={{color:'#fff'}}
                    rightTextPress={()=>this.finished()}/>
                <LoadingModal visible={this.state.load} onRequestClose={()=>{console.log('666')}}/>
                <ScrollView>
                    <View style={{backgroundColor:'#fff',height:30,alignItems:'center',paddingLeft:10,flexDirection:'row'}}>
                        <Text style={styles.textColor}>*</Text><Text>商品缩略图：</Text></View>
                    <View style={styles.addImgBox}>
                        <TouchableOpacity onPress={()=>this.choseImg()}>
                            { this.state.avatarSource.path ?
                                <Image style={{width:80,height:80}}
                                    source={{uri:this.state.avatarSource.path}} /> :
                                <ImageWrapper width={80} height={80} icon={'addImg'}/>
                            }
                        </TouchableOpacity>
                    </View>
                    <View style={styles.bgImages}>
                        <View style={styles.textBox}><Text style={styles.textColor}>*</Text><Text>商品轮播图(最多添加5张)：</Text></View>
                        <View style={styles.imagesBox}>
                            {this.renderImages('swiper',this.state.swiperImageUrl)}
                            <TouchableOpacity onPress={()=>this.addImages('swiper',5)}>
                                <ImageWrapper style={{marginTop:10}} width={60} height={60} icon={'addImg'}/>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={styles.bgImages}>
                        <View style={styles.textBox}><Text style={styles.textColor}>*</Text><Text>商品详情图(最多添加9张)：</Text></View>
                        <View style={styles.imagesBox}>
                            {this.renderImages('detail',this.state.detailImageUrl)}
                            <TouchableOpacity onPress={()=>this.addImages('detail',9)}>
                                <ImageWrapper style={{marginTop:10}} width={60} height={60} icon={'addImg'}/>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={{paddingLeft:10,backgroundColor:'#fff',borderBottomWidth:1,borderBottomColor:'#ccc'}}>
                        <GoodsItem style={styles.itemBorder} title={'商品名称'} hasInput={true}
                            placeholder={'请输入商品名称'} defaultValue={this.state.g_name} onChangeText={(text)=>this.getGoodsName(text)} onBlur={()=>this.editGoods('g_name')}/>
                        <GoodsItem style={styles.itemBorder} title={'品牌'} hasInput={true}
                            placeholder={'请输入品牌'} defaultValue={this.state.g_cate} onChangeText={(text)=>this.getGoodsCate(text)} onBlur={()=>this.editGoods('g_cate')}/>
                        <View style={{borderBottomWidth:1,borderBottomColor:'#DFDFE2',flexDirection:'row'}}>
                            <View style={[styles.textBox,{width:70,marginRight:20}]}>
                                <Text style={styles.textColor}>*</Text>
                                <Text>商品介绍</Text>
                            </View>
                            <View style={{flex:1,paddingTop:3}}>
                                <TextInput 
                                    style={{padding:3,fontSize:12}}
                                    underlineColorAndroid={'transparent'}
                                    textAlignVertical={'top'}
                                    multiline={true}
                                    numberOfLines={5}
                                    placeholder={'请输入商品介绍'}
                                    onChangeText={(text)=>this.getGoodsIntroduce(text)}
                                    defaultValue={this.state.g_jieshao}
                                    onBlur={()=>this.editGoods('g_jieshao')}/>
                            </View>
                        </View>
                        <GoodsItem style={styles.itemBorder} title={'库存'} hasInput={true}
                            placeholder={'请输入库存'} defaultValue={this.state.g_num} onChangeText={(text)=>this.getGoodsNum(text)} onBlur={()=>this.editGoods('g_num')}/>
                        <GoodsItem style={styles.itemBorder} title={'库存警戒值'} hasInput={true}
                            placeholder={'请输入库存警戒值'} defaultValue={this.state.g_num_danger} onChangeText={(text)=>this.getGoodsNumDanger(text)} onBlur={()=>this.editGoods('g_num_danger')}/>
                        <GoodsItem style={styles.itemBorder} title={'售价'} hasInput={true}
                            placeholder={'请输入售价'} defaultValue={this.state.g_price}  onChangeText={(text)=>this.getGoodsPrice(text)} onBlur={()=>this.editGoods('g_price')}/>
                        <GoodsItem title={'采购价'} hasInput={true}
                            placeholder={'请输入采购价'} defaultValue={this.state.g_get_price}  onChangeText={(text)=>this.getGoodsGetPrice(text)} onBlur={()=>this.editGoods('g_get_price')}/>
                    </View>
                    <View style={{marginTop:20,marginBottom:20}}>
                        {this.state.staturs=='添加商品'?<TouchableOpacity onPress={()=>this.publicGoods()} style={styles.buttonBox}>
                            <View style={[styles.button,{backgroundColor:'#0894ED'}]}>
                                <Text style={{color:'#fff'}}>发布</Text>
                            </View>
                        </TouchableOpacity>:this.renderButton()}
                    </View>

                </ScrollView>
                
            </View>
        )

    }
    // 返回按钮
    goBack(){
        this.props.navigation.goBack();
    }
    /*
    * 编辑商品时右上角完成按钮
    */
    finished(){
        this.props.navigation.state.params.upData();
        this.goBack();
    }
    // 选择多张图片
    addImages(staturs,length){
        var $this = this;
        if(staturs=='swiper'&&this.state.swiperImageUrl.length>=5){
            return;
        }else if(staturs=='detail'&&this.state.detailImageUrl.length>=9){
            return;
        }
        ImageCropPicker.openPicker({
            multiple: true,
            maxFiles: 9,
            mediaType: 'photo'
        }).then(images => {
            var len = images.length;
            var arr = [];
            for(var i=0;i<len;i++){
                var source = {};
                if (Platform.OS === 'android') {
                    source = {path: images[i].path};
                    arr.push(source);
                } else {
                    source = {path: images[i].path.replace('file://', '')};
                    arr.push(source);
                }
            }
            var uriArr = [];
            var dataArr = [];
            if(staturs=='swiper'){
                uriArr = $this.state.swiperImageUrl;
                dataArr = $this.state.swiperImageData;
            }else if(staturs=='detail'){
                uriArr = $this.state.detailImageUrl;
                dataArr = $this.state.detailImageData;
            }
            uriArr = uriArr.concat(arr);
            dataArr = dataArr.concat(images);
            if(uriArr.length>length){
                uriArr.splice(length);
                dataArr.splice(length);
            }
            if(staturs=='swiper'){
                $this.setState({
                    swiperImageUrl:uriArr,
                    swiperImageData:dataArr
                })
            }else if(staturs=='detail'){
                $this.setState({
                    detailImageUrl:uriArr,
                    detailImageData:dataArr
                })
            }
        }).catch((err)=> {
                console.log(err);
            });
    }
    // 删除图片
    selectItem(staturs,index){
        var imgList = [];
        var dataList = [];
        if(staturs=='swiper'){
            alert(1)
            imgList = this.state.swiperImageUrl;
            dataList = this.state.swiperImageData;
        }else if(staturs=='detail'){
            imgList = this.state.detailImageUrl;
            dataList = this.state.detailImageData;
        }
        imgList.splice(index,1);
        dataList.splice(index,1);
        if(staturs=='swiper'){
            this.setState({
                swiperImageUrl:imgList,
                swiperImageData:dataList
            })
        }else if(staturs=='detail'){
            this.setState({
                detailImageUrl:imgList,
                detailImageData:dataList
            })
        }
    }
    // 获取商品名称
    getGoodsName(text){
        this.setState({
            g_name:text
        })
    }
    // 获取商品品牌
    getGoodsCate(text){
        this.setState({
            g_cate:text
        })
    }
    // 获取商品介绍
    getGoodsIntroduce(text){
        this.setState({
            g_jieshao:text
        })
    }
    // 获取商品数量
    getGoodsNum(text){
        this.setState({
            g_num:text
        })
    }
    // 获取商品警戒值
    getGoodsNumDanger(text){
        this.setState({
            g_num_danger:text
        })
    }
    // 获取售价
    getGoodsPrice(text){
        this.setState({
            g_price:text
        })
    }
    // 获取采购价
    getGoodsGetPrice(text){
        this.setState({
            g_get_price:text
        })
    }
    // 编辑时获取商品详情
    getGoodsData(){
        var $this = this;
        shopService.shopGoodsIdInfo(function(data){
            // alert(JSON.stringify(data));
            if(data.code){
                var obj = data.data;
                var imgObj = {path:'http://peita.oss-cn-beijing.aliyuncs.com/'+obj.g_img}
                var swiper = obj.g_img_lunbo.split(',');
                var detail = obj.g_img_info.split(',');
                var swiperList = [];
                var detailList = [];
                var swiperDataList = [];
                var detailDataList = [];
                var swiperLen = swiper.length;
                var detailLen = detail.length;
                for(var i=0;i<swiperLen;i++){
                    if(swiper[i]!=''){
                        var object = {};
                        object.path = 'http://peita.oss-cn-beijing.aliyuncs.com/'+swiper[i];
                        swiperList.push(object);
                        swiperDataList.push(object);
                    }
                }
                for(var i=0;i<detailLen;i++){
                    if(detail[i]!=''){
                        var object = {};
                        object.path = 'http://peita.oss-cn-beijing.aliyuncs.com/'+detail[i];
                        detailList.push(object);
                        detailDataList.push(object);
                    }
                }
                $this.setState({
                    g_cate:obj.g_cate,
                    g_num:obj.g_num,
                    g_num_danger:obj.g_num_danger,
                    g_price:obj.g_price,
                    g_get_price:obj.g_get_price,
                    shopName:obj.merchant_name,
                    g_name:obj.g_name,
                    resultImageData : imgObj,
                    avatarSource:imgObj,
                    goodsData:obj,
                    g_is_show:obj.g_is_show,
                    swiperImageUrl:swiperList,
                    swiperImageData:swiperDataList,
                    detailImageUrl:detailList,
                    detailImageData:detailDataList,
                    g_jieshao:obj.g_jieshao,
                })
            }
        },$this.state.g_id,$this.token)
    }
    // 选择头像上传
    choseImg(){
        var $this = this;
        
        ImageCropPicker.openPicker({
            width: 300, 
            height: 300, 
            cropping: true,
            mediaType:'photo',
        }).then(image =>{ 
            var source;
            if (Platform.OS === 'android') {
                source = {path: image.path, isStatic: true};
            } else {
                source = {path: image.path.replace('file://', ''), isStatic: true};
            }
            // alert(JSON.stringify(source))
            $this.setState({
                avatarSource : source,
                resultImageData : image,
            });
            if(this.state.staturs=='编辑商品'){
                var imgArr = [];
                var params = {};
                imgArr['g_img'] = image.path;
                params.g_id = $this.state.g_id;
                params.type = 1;
                shopService.myShopGoodsIdSave(function(data){
                    alert(JSON.stringify(data));
                    if(data.code==10000){
                        console.log('666');
                    }
                },params,imgArr,$this.token)
            }
        }).catch((err)=> {
                console.log(err);
            });        
    }
    // 修改商品内容
    editGoods(name){
        $this = this;
        if(this.state.staturs=='编辑商品'&&(name=='g_img' || this.state.goodsData[name]!=this.state[name])){
            var obj = {
                'g_img':1,
                'g_cate':2,
                'g_num':3,
                'g_num_danger':4,
                'g_price':5,
                'g_get_price':6,
                'g_is_show':8,//是否上架(1.上架2.下架),
                'g_name':9,
                'g_img_lunbo':10,
                'g_img_info':11,
                'g_jieshao':12,
            }
            var imgArr = [];
            var params = {};
            if(name=='g_img'){
                imgArr['g_img'] = this.state.resultImageData.path;
            }else{
                params[name] = this.state[name];
            }
            params.g_id = this.state.g_id;
            params.type = obj[name];
            shopService.myShopGoodsIdSave(function(data){
                // alert(JSON.stringify(data));
                if(data.code==10000){
                    console.log('666');
                }
            },params,imgArr,$this.token)
        }
        
    }
    // 点击上架下架按钮
    async clickButton(){
        var statursNum = this.state.g_is_show;
        if(statursNum==1){
            statursNum = 2;
        }else{
            statursNum = 1;
        }
        await this.setState({
            g_is_show:statursNum
        })
        var params = {};
        params.g_is_show = statursNum;
        params.g_id = this.state.g_id;
        params.type = 8;
        shopService.myShopGoodsIdSave(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                console.log('666');
            }
        },params,[],$this.token)
    }
    // 发布商品
    publicGoods(){
        var $this = this;
        if(!this.state.resultImageData.path){
            alert('请添加商品图！');
            return;
        }else if(this.state.g_name.replace(/^\s$/g,'')==''){
            alert('请输入商品名称！');
            return;
        }else if(this.state.g_jieshao.replace(/^\s$/g,'')==''){
            alert('请输入商品介绍！');
            return;
        }else if(this.state.g_cate.replace(/^\s$/g,'')==''){
            alert('请输入品牌！');
            return;
        }else if(this.state.g_num.replace(/^\s$/g,'')==''){
            alert('请输入库存！');
            return;
        }else if(this.state.g_num_danger.replace(/^\s$/g,'')==''){
            alert('请输入警戒值！');
            return;
        }else if(this.state.g_price.replace(/^\s$/g,'')==''){
            alert('请输入售价！');
            return;
        }else if(this.state.g_get_price.replace(/^\s$/g,'')==''){
            alert('请输入采购价！');
            return;
        }else{
            var imgArr = [];
            imgArr['img'] = this.state.resultImageData.path;
            var list = this.state.swiperImageData.concat(this.state.detailImageData);
            var listLen = list.length;
            var upFileArr = [];
            var swiperLen = this.state.swiperImageData.length;
            for(var i=0;i<listLen;i++){
                upFileArr['img'+(i+1)] = list[i].path;
            }
            this.setState({
                load:true
            })
            shopService.upFile(function(result){
                // alert(JSON.stringify(result));
                if(result.code==10000){
                    var resultList = result.data.split(',');
                    var swiper = '';
                    var detail = '';
                    swiper = resultList.splice(0,swiperLen).join(',');
                    detail = resultList.join(',');
                    // alert(swiper+'-----'+detail)
                    shopService.addShopGoods(function(data){
                        // alert(JSON.stringify(data));

                        if(data.code==10000){
                            $this.setState({
                                load:false
                            })
                            Alert.alert(
                                '提示信息',
                                '发布成功',
                                [{text: '确定', onPress: () => {$this.props.navigation.state.params.upData();$this.goBack()}}])
                        }
                    },$this.state.g_name,$this.state.g_cate,$this.state.g_num,$this.state.g_num_danger,$this.state.g_price,$this.state.g_get_price,$this.userId,$this.shopId,$this.state.g_jieshao,swiper,detail,imgArr,$this.token)
                }
            },upFileArr,$this.token)
            
        }
    }


}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },
        }),
    },
    addImgBox:{
        justifyContent:'center',
        alignItems:'center',
        height:100,
        backgroundColor:'#EFEFF4',
    },
    button:{
        width:3*width/4,
        borderRadius:5,
        justifyContent:'center',
        alignItems:'center',
        height:40
    },
    buttonBox:{
        alignItems:'center'
    },
    itemBorder:{
        borderBottomWidth:1,
        borderBottomColor:'#DFDFE2'
    },
    imagesBox:{
        flexDirection:'row',
        paddingLeft:10,
        paddingBottom:10,
        paddingRight:10,
        flexWrap:'wrap'
    },
    bgImages:{
        backgroundColor:'#fff',
        borderBottomWidth:1,
        borderBottomColor:'#E1E1E4',
        paddingLeft:10
    },
    textColor:{
        color:'red'
    },
    textBox:{
        flexDirection:'row',
        height:30,
        alignItems:'center'
    }
});